package cc.mrbird.febs.system.controller;


import cc.mrbird.febs.common.annotation.Log;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.domain.FebsResponse;
import cc.mrbird.febs.common.domain.QueryRequest;
import cc.mrbird.febs.common.exception.FebsException;
import cc.mrbird.febs.system.domain.TResident;
import cc.mrbird.febs.system.service.ITResidentService;
import cc.mrbird.febs.system.vo.TResidentExcelVO;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.wuwenze.poi.ExcelKit;
import com.wuwenze.poi.handler.ExcelReadHandler;
import com.wuwenze.poi.pojo.ExcelErrorField;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

/**
 * @author dtwei
 */
@Slf4j
@RestController
@RequestMapping("/tResident")
public class TResidentController extends BaseController {

    private String message;

    @Resource
    private ITResidentService residentService;

    @GetMapping
    @RequiresPermissions("rs:view")
    public Map<String, Object> rsList(QueryRequest queryRequest, TResident rs, String areaName) {
        return getDataTable(this.residentService.findResidentPage(rs, areaName, queryRequest));
    }

    @Log("新增住户")
    @PostMapping
    @RequiresPermissions("rs:add")
    @Transactional(rollbackFor = Exception.class)
    public FebsResponse addHouse(@RequestBody @Valid TResident rs) throws FebsException {
        try {
            this.residentService.createRs(rs);
            return new FebsResponse().code("200").message("新增住户成功").status("success");
        } catch (FebsException e) {
            throw e;
        } catch (Exception e) {
            message = "新增住户失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("删除住户")
    @DeleteMapping
    @RequiresPermissions("rs:delete")
    @Transactional(rollbackFor = Exception.class)
    public FebsResponse deleteShops(@NotBlank(message = "{required}") String rsIds) throws FebsException {
        try {
            String[] ids = rsIds.split(StringPool.COMMA);
            this.residentService.deleteRs(ids);
            return new FebsResponse().code("200").message("删除住户成功").status("success");
        } catch (FebsException e) {
            throw e;
        } catch (Exception e) {
            message = "删除住户失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("修改住户")
    @PutMapping
    @RequiresPermissions("rs:update")
    @Transactional(rollbackFor = Exception.class)
    public FebsResponse updateShop(@RequestBody @Valid TResident rs) throws FebsException {
        try {
            this.residentService.updateRs(rs);
            return new FebsResponse().code("200").message("修改住户成功").status("success");
        } catch (FebsException e) {
            throw e;
        } catch (Exception e) {
            message = "修改住户失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("导入住户")
    @PostMapping(value = "/import")
    @RequiresPermissions("rs:import")
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importShops(MultipartFile file) throws FebsException {
        try {
            long beginMillis = System.currentTimeMillis();

            List<Map<String, Object>> successList = Lists.newArrayList();
            List<Map<String, Object>> errorList = Lists.newArrayList();

            ExcelKit.$Import(TResidentExcelVO.class)
                    .readXlsx(file.getInputStream(), new ExcelReadHandler<TResidentExcelVO>() {

                        @Override
                        public void onSuccess(int sheetIndex, int rowIndex, TResidentExcelVO entity) {
                            successList.add(
                                    ImmutableMap.of("sheetIndex", sheetIndex,//
                                            "rowIndex", rowIndex,//
                                            "entity", entity)
                            );
                        }

                        @Override
                        public void onError(int sheetIndex, int rowIndex,
                                            List<ExcelErrorField> errorFields) {
                            // 读取数据失败，记录了当前行所有失败的数据
                            errorList.add(
                                    ImmutableMap.of("sheetIndex", sheetIndex,//
                                            "rowIndex", rowIndex,//
                                            "errorFields", errorFields)
                            );
                        }
                    });

            List<Map<String, Object>> secImport = this.residentService.importRs(successList);
            if (null != secImport && !secImport.isEmpty()) {
                errorList.addAll(secImport);
            }

            if (errorList.isEmpty()) {
                return new FebsResponse().code("200").message("导入住户成功").status("success");
            } else {
                return new FebsResponse().code("500").message("导入住户失败").status("fail").data(errorList);
            }
        } catch (Exception e) {
            message = "导入住户失败：" + e.getMessage();
            log.error(message, e);
            throw new FebsException(message);
        }
    }
}
